<style>
.from-div {
    background-color: white;
    margin: 4px;
    position: relative;
}
.from-title {
    position: relative;
    display: flex;
    justify-content: space-between;
    width: 100%;
    line-height: 32px;
    padding: 10px;
    border-bottom: 1px solid #e7e9e9;
}


</style>
<template>
<div id="from-div" class="from-div">
      <Row>
          <Col span="24">
            <div class="from-title">
                <h3>新闻添加</h3>
                <div>
                    <Button :loading="saveLoading" style="margin-right: 10px;" type="primary" @click="handleSubmit">添加</Button>
                    <Button type="primary" icon="android-arrow-back" @click="goBack">返回</Button>                          
                </div>
            </div>
          </Col>
      </Row>
      </br>
      <Row>
          <Col span="18" offset="3">
            <div id="from-item">
                <Form ref="dataFrom" label-position="top" :model="item" :rules="rules"><!--  -->
                    <FormItem label="标题" prop="title">
                        <Input ref="title" v-model="item.title" placeholder="请输入标题"></Input>
                    </FormItem>
                    <FormItem label="地区" prop="city">
                        <Select
                            ref="city"
                            placeholder="请输关键词搜索......"
                            v-model="item.city"
                            filterable
                            remote
                            :remote-method="remoteCity"
                            :loading="sloading">
                            <Option v-for="(city, index) in cities" :value="city.cityName" :key="index">{{city.cityName}}</Option>
                        </Select>
                    </FormItem>
                    <FormItem label="封面（400 X 158）" prop="" required>
                        <tupload :uploadRef="coref" :maxImgNum="maxImgNum"
                            @uploadSuccess="handleCoverUpload"></tupload>
                    </FormItem>
                    <FormItem class="fullWidth" label="介绍" prop="summary" required>
                        <editor ref="summary" @onChange="handleEditChange"></editor>
                    </FormItem>
                </Form>
            </div>
          </Col>
      </Row>
  </div>
</template>
<script>
import tupload from '../my-components/upload/upload';
import editor from '../my-components/text-editor/text-editor';
export default {
    components: {
        tupload,
        editor
    },
    data () {
        return {
            cities: [],
            sloading: false,
            saveLoading: false,
            coref: 'cover',
            maxImgNum: 1,
            item: {
                title: '',
                city: '',
                cover: '',
                summary: ''
            },
            rules: {
                title: [
                    { required: true, message: '请输入标题', trigger: 'blur' }
                ],
                city: [
                    { required: true, message: '请输入地区', trigger: 'blur' }
                ]
            }
        };
    },

    methods: {
        goBack () {
            window.history.go(-1);
        },
        getData () {

        },
        remoteCity (query) {
            if (query !== '') {
                this.sloading = true;
                this.$post('/city/search', {name: query})
                    .then(res => {
                        this.sloading = false;
                        this.cities = res;
                    })
                    .catch(error => {
                        this.sloading = false;
                    });
            } else {
                this.cities = [];
                this.sloading = true;
            }
        },
        handleCoverUpload (url) {
            this.item.cover = url;
        },
        handleSubmit () {
            if (this.item.cover === '') {
                return this.$Message.error('请上传封面图！');
            }
            if (this.item.summary === '') {
                return this.$Message.error('请输入介绍！');
            }
            this.$refs.dataFrom.validate((valid) => {
                if (valid) {
                    this.saveLoading = true;
                    this.$post('/news/save', this.item, 'json')
                        .then(res => {
                            this.saveLoading = false;
                            this.$Message.success('添加成功');
                            this.$router.push({
                                name: 'news-index'
                            });
                        })
                        .catch(error => {
                            this.saveLoading = false;
                            this.$Message.error(error.msg || error.message);
                        });
                } else {
                    let fields = this.$refs.dataFrom.fields;
                    try {
                        fields.forEach(element => {
                            if (element.validateState === 'error') {
                                let refName = element.prop;
                                this.$refs[refName].focus();
                                foreach.break = new Error('StopIteration');
                            }
                        });
                    } catch (e) {
                        console.log(e);
                    }
                }
            });
        },

        handleEditChange (content) {
            this.item.summary = content;
        }
    },
    created () {
        this.getData();
        this.remoteProtocol('NAN');
    }
};
</script>
